package com.yl.auth.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yl.auth.entity.HugongLaoren;
import com.yl.auth.entity.LaorenTijian;
import com.yl.auth.entity.Yaopin;
import com.yl.auth.model.entity.HuLao;
import com.yl.auth.model.entity.JiaShu;
import com.yl.auth.model.entity.Tijian;
import com.yl.auth.model.vo.LaorenVo;
import com.yl.auth.entity.Yongyao;
import com.yl.auth.service.*;
import com.yl.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yl
 * @since 2023-06-16
 */
@RestController
@RequestMapping("/admin/auth/hugonglaoren")
@Api(tags = "机构端-医护管理")
public class HugongLaorenController {
    @Resource
    private HugongLaorenService hugongLaorenService;
    @Resource
    private YaopinService yaopinService;
    @Resource
    private JiaShuService jiaShuService;
    @Resource
    private LaorenTijianService laorenTijianService;
    @Resource
    private TijianService tijianServicel;

    /**
     * 存药登记分页模糊查询
     * @param page
     * @param limit
     * @param name
     * @return
     */
    @GetMapping("/findAllConn/{page}/{limit}")
    @ApiOperation(value = "存药分页模糊查询")
    public Result findAllConn(@PathVariable @ApiParam("页码") Long page,
                              @PathVariable @ApiParam("记录") Long limit,
                              @ApiParam("老人姓名") String name,@ApiParam("登记时间") String dengjiTime){
        Page<LaorenVo> page1=new Page<>(page,limit);
        Page<LaorenVo> allConn = hugongLaorenService.findAllConn(page1, name,dengjiTime);
        return Result.ok(allConn);
    }

    /**
     * 用药登记-老人信息
     */
    @ApiOperation(value = "用药登记-老人信息")
    @GetMapping("/getLaoren/{id}")
    public Result getLaoren(@PathVariable @ApiParam("老人id") Long id){
        HugongLaoren hugongLaoren=hugongLaorenService.getLaoren(id);
        return Result.ok(hugongLaoren);
    }

    /**
     * 用药登记根据id分页查询
     */
    @GetMapping("/getByIdList/{id}")
    @ApiOperation(value = "用药登记")
    public Result getByIdList(@PathVariable @ApiParam("老人id") Integer id,
                              HugongLaoren hugongLaoren){
        List<LaorenVo> page1=hugongLaorenService.getByIdList(id,hugongLaoren);
        return Result.ok(page1);
    }



    /**
     * 根据id删除
     */
    @DeleteMapping("/remove/{id}")
    @ApiOperation(value = "删除存药登记")
    public Result remove(@PathVariable @ApiParam("老人id") Integer id){
        hugongLaorenService.remove(id);
        return Result.ok();
    }

//    /**
//     * 新增
//     */
//    @ApiOperation(value = "查询老人所用药品信息")
//    @GetMapping("/save/{id}")
//    public Result save(@PathVariable @ApiParam("老人id") Long id){
//        //点击编辑按钮跳转页面，首先先根据id查询老人所用药品信息，
//        //然后在点击编辑按钮或者是删除按钮来进行编辑和删除操作
//        List<Yaopin> yaopinList=hugongLaorenService.getYaopin(id);
//        //点击新增按钮跳转页面，新增就是新增，不用回显老人药品的信息
//
//        return Result.ok();
//    }



    /**
     * 存药登记根据id查看详情
     */
    @ApiOperation(value = "存药登记查看详情")
    @GetMapping("/getCunyao/{id}")
    public Result getCunyao(@PathVariable @ApiParam("记录表id") Integer id){
        //根据记录表id查询老人登记的一条记录里面的药品详情
        List<LaorenVo> list =hugongLaorenService.getCunyao(id);
        return Result.ok(list);
    }

    /**
     * 新增药品
     * 问题：怎么查询刚新增的这条数据，SELECT * FROM table_name ORDER BY id DESC LIMIT 1;
     */
    @ApiOperation(value = "新增药品")
    @PostMapping("/save")
    public Result save(@RequestBody Yaopin yaopin){
        yaopinService.save(yaopin);
        return Result.ok(yaopin);
    }

    /**
     * 查询最新添加的这条数据
     */
    @ApiOperation(value = "查询最新添加的一条数据")
    @GetMapping("/getzuixin")
    public Result getzuixin(){
        Yaopin yaopin=yaopinService.getzuixin();
        return Result.ok(yaopin);
    }

    /**
     * 根据id删除药品
     */
    @ApiOperation(value = "根据id删除药品")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable @ApiParam("药品id") Long id){
        yaopinService.removeById(id);
        return Result.ok();
    }

    /**
     * 根据id回显老人药品
     */
    @ApiOperation(value = "根据id回显老人药品")
    @GetMapping("/getyaopin/{id}")
    public Result getyaopin(@PathVariable @ApiParam("存药记录id") Long id){
        List<LaorenVo> list =hugongLaorenService.getyaopin(id);
        return Result.ok(list);
    }

    /**
     * 编辑药品
     */
    @ApiOperation(value = "编辑药品")
    @PutMapping("/update")
    public Result update(@RequestBody Yaopin yaopin){
        yaopinService.updateById(yaopin);
        return Result.ok();
    }

    /**
     * 查询家属
     */
    @ApiOperation(value = "查询家属")
    @GetMapping("/getjiashu")
    public Result getjiashu(){
        List<JiaShu> list=jiaShuService.list();
        return Result.ok(list);
    }

    /**
     * 新增用药登记
     */
    @ApiOperation(value = "新增用药登记")
    @PostMapping("/saveyongyao")
    public Result saveyongyao(@RequestBody Yongyao yongyao){
        //给记录表添加了一条数据
        hugongLaorenService.save(yongyao.getHugongLaoren());
        //循环给已经添加的药品数据赋记录表的外键
        yaopinService.add(yongyao.getHugongLaoren().getId(),yongyao.getArrlist());
        return Result.ok(yongyao.getHugongLaoren());
    }


//    /*图片上传上传图片接口*/
//    /*图片上传地址*/
//    //String fileSavePath = "D:/IDEABoot课程/ylHomes/service-ylHouse/src/main/resources/templates/upload/";
//    @Value("${web.upload-path}")
//    private String fileSavePath;
//    //String fileSavePath = "D\\:/BaiduNetdiskDownload/jiushuifile/";
//    @PostMapping("/saveUpload")
//    @ApiOperation(value = "图片上传")
//    @CrossOrigin
//    public Result uploadFile (@ApiParam(name = "file", value = "上传", required = true) @RequestPart("file") List<MultipartFile> file, HttpServletRequest request) throws IOException {
//        /*格式化时间*/
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
//        /*将时间转化成字符串*/
//        Date date = new Date();
//        String directory = simpleDateFormat.format(date);
//        List<String> a = new ArrayList<String>();
//        for (MultipartFile multipartFile : file) {
//            /*获取图片的名字*/
//            String imageName = multipartFile.getOriginalFilename();
//            /*文件路径是否存在
//             * 如果不存在,则创建
//             */
//            File dir = new File(fileSavePath +"/upload/" + directory);
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//            System.out.println("图片上传位置" + fileSavePath + directory);
//            /*给文件创建一个新的名字*/
//            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
//            /*图片新的名字*/
//            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
//            System.out.println("上传的图片位置" + fileSavePath + directory + newFileName);
//            /*创建新文件*/
//            File newFile = new File(fileSavePath +"/upload/" + directory + newFileName);
//            multipartFile.transferTo(newFile);
//            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
//            System.out.println("图片上传成功的url:" + url);
//            String sql = "/upload/" + directory + newFileName;
//            a.add(sql);
//            /*返回给前端的字符串地址,然后添加的时候将这一串字符串加入到数据库中*/
////            return Result.ok(sql);
//            System.out.println(sql);
//        }
//        //将集合所有的数据末尾加逗号拼接成字符串存入数据库中
//        String result = a.stream().collect(Collectors.joining(","));
//        System.out.println(result);
//        return Result.ok(result);
//    }


    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    /*图片上传上传图片接口*/
    /*图片上传地址*/
    String fileSavePath = "D:\\vscode2209\\codeylhomes\\public\\upload/";
    /*格式化时间*/
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

    @PostMapping("/saveUpload")
    @ApiOperation(value = "图片上传")
    @CrossOrigin
    public Result uploadFile(@ApiParam(name = "file", value = "上传", required = true) @RequestPart("file") MultipartFile file, HttpServletRequest request) {
        /*将时间转化成字符串*/
        Date date = new Date();
        String directory = simpleDateFormat.format(date);
        /*文件路径是否存在
         * 如果不存在,则创建
         */
        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        /*获取图片的名字*/
        String imageName = file.getOriginalFilename();
        System.out.println("图片上传位置" + fileSavePath + directory);
        /*给文件创建一个新的名字*/
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        /*图片新的名字*/
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        System.out.println("上传的图片位置" + fileSavePath + directory + newFileName);
        /*创建新文件*/
        File newFile = new File(fileSavePath + directory + newFileName);
        try {
            file.transferTo(newFile);
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
            System.out.println("图片上传成功的url:" + url);
            String sql = "/upload/" + directory + newFileName;
            /*返回给前端的字符串地址,然后添加的时候将这一串字符串加入到数据库中*/
            return Result.ok(sql);
        } catch (IOException e) {
            return Result.ok();
        }
    }

    /**
     * 66666666
     */
    @ApiOperation(value = "￥￥￥￥")
    @GetMapping("/getss/{id}")
    public Result getss(@PathVariable Integer id){
        LaorenTijian laorenTijian = new LaorenTijian();
        laorenTijian.setLid(id);
        laorenTijian.setShangchuanTime(LocalDateTime.now());
        laorenTijianService.save(laorenTijian);
        return Result.ok();
    }

    /**
     * 存药详情上
     */
    @ApiOperation(value = "存药详情上")
    @GetMapping("/getcunshang/{id}")
    public Result getcunshang(@PathVariable @ApiParam("记录表id") Integer id){
        LaorenVo list=hugongLaorenService.getcunshang(id);
        return Result.ok(list);
    }

    @ApiOperation(value = "根据id查询药品")
    @GetMapping("getDrug/{id}")
    public Result getDrug(@PathVariable Integer id){
        Yaopin byId = yaopinService.getById(id);
        return Result.ok(byId);
    }

    /**
     * 修改用药登记
     */
    @ApiOperation(value = "修改用药登记")
    @PostMapping("updateyongyao")
    public Result updateyongyao(@RequestBody Yongyao yongyao){
        //给记录表添加了一条数据
        HugongLaoren byId =  hugongLaorenService.getjilu(yongyao.getId());
        byId.setJingbanren(yongyao.getHugongLaoren().getJingbanren());
        hugongLaorenService.updateById(byId);
        //循环给已经添加的药品数据赋记录表的外键
        yaopinService.add(yongyao.getHugongLaoren().getId(),yongyao.getArrlist());
        return Result.ok(yongyao.getHugongLaoren());
    }

    @ApiOperation(value = "根据id获取记录信息")
    @GetMapping("getjilubiao/{id}")
    public Result getjilubiao(@PathVariable Integer id){
        HugongLaoren byId =  hugongLaorenService.getjilu(id);
        return Result.ok(byId);
    }


}

